package org.jeecg.config.binlog;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * @author gbstart
 * @create 2024-06-04 21:37
 */
@Slf4j
@Component
@Order(value = 1)
public class TslBinLogListener implements CommandLineRunner {

    @Autowired
    RedisUtil redisUtil;

    @Resource
    private BinLogConstants binLogConstants;

    @Autowired
    ChangeDataAutoRecordtwo changeDataAutoRecordtwo;

    @Override
    public void run(String... args) throws IOException, TimeoutException {
        // 初始化监听器
        MysqlBinLogListener mysqlBinLogListener = new MysqlBinLogListener(binLogConstants);
        List<String> tableList = (List<String>) redisUtil.get("tablelist");
        System.out.println(tableList);
        // 获取table集合
//        List<String> tableList = BinLogUtils.getListByStr(binLogConstants.getTable());
        if (CollectionUtil.isEmpty(tableList)) {
            return;
        }
        log.info("注册监听信息");
        // 注册监听
        tableList.forEach(table -> {
            String substring = binLogConstants.getUrl().substring(binLogConstants.getUrl().lastIndexOf("//")+2);
            String db = substring.substring(substring.indexOf("/") + 1, substring.indexOf("?"));
            //log.info("注册监听信息，注册DB：" + db + "，注册表：" + table);
            try {
                mysqlBinLogListener.regListener(db, table, item -> {
                    log.info("监听逻辑处理",table);
                    try {
                        changeDataAutoRecordtwo.messageChange(item,table);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                log.error("BinLog监听异常：" + e);
            }
        });
        // 多线程消费
        mysqlBinLogListener.parse();
    }

}
